import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

player_df = pd.read_csv('../篮球球员效率值/data/player_data.csv')

player_df.head()  # 查看前五行记录

# 查找缺失值
player_df.isna().sum()


# 删除列
# 删除所有为空值的列
player_df.dropna(inplace=True, axis="columns", how='all')


# 删除行
# 删除所有为空的行
player_df.dropna(inplace=True, how="all")
player_df.isna().sum()

# 删除每行少于12个非空字段的记录
player_df.dropna(inplace=True, thresh=12)
player_df.isna().sum()


# 重置索引
player_df.reset_index(inplace=True, drop=True)


# 检查离群值
player_df.describe()

# 创建列的箱线图

cols = list(player_df.iloc[:, 1:])

# 创建3x5的平铺图矩阵
fig, axes = plt.subplots(3, 5, figsize=(18, 11))

# 各个子图设置2像素间距方便读取
fig.tight_layout(pad=2.0)

# 为每个列绘制箱线图，并填入到子图
for i in range(len(cols)):
    sns.boxplot(ax=axes[i//5, i % 5], y=player_df[cols[i]])

# 通过箱线图发现字段‘point’与‘possensions’存在离群值
# 识别并删除包含离群值的行
points_outlier = player_df['points'].idxmin()  # 返回最小值的索引
possession_outlier = player_df['possessions'].idxmin()

# 惊奇发现两个最小值对应的索引相同（35）
player_df.drop(player_df.index[points_outlier], inplace=True)  # 删除第35行记录

player_df.tail(10)  # 查看最后10行数据

player_df.reset_index(inplace=True, drop=True)


player_df.isna().sum()

# Create a list of all column names, except for 'ID'.
cols = list(player_df.iloc[:, 1:])

# Define the size for the plots and add padding around them.
fig1 = plt.figure(figsize=(18, 11))
fig1.tight_layout(pad=5.0)

# Loop over the columns in the DataFrame and create a histogram for each one.
for i in range(len(cols)):
    plt.subplot(3, 5, i+1)
    plt.hist(player_df[cols[i]], bins=30)
    plt.title(cols[i])
